package Server.impl;
import BaseQuery.CartQuery;
import BaseQuery.BaseQuery;
import Bean.Cart;
import Dao.ICartDao;
import Dao.impl.CartDao;
import Server.ICartServe;
import com.alibaba.druid.util.StringUtils;
import vo.PageBean;
import vo.ResultBean;

import java.sql.SQLException;
import java.util.List;

public class CartServe implements ICartServe {
	private ICartDao cartDao;

	public CartServe() {
		cartDao=new CartDao();
	}

	@Override
	public ResultBean add(Cart cart) throws Exception {
		System.out.println("添加操作");
		if (cart==null || cart.getBusinessId()==null){
			return ResultBean.ERROR(10001,"params null");
		}

		int i = cartDao.add(cart);
		return i>0?ResultBean.SUCCESS():ResultBean.ERROR("add cart fail");
	}

	@Override
	public ResultBean update(Cart cart) throws Exception {
		System.out.println("修改操作");
		if (cart.getCartId()==null||cart.getBusinessId()==null){
			return ResultBean.ERROR(10001,"params null");
		}
		int i = cartDao.update(cart);
		System.out.println(i);
		return i>0?ResultBean.SUCCESS():ResultBean.ERROR("update cart fail");
	}

	@Override
	public ResultBean delete(Integer id) throws Exception {
		//想办法如何告知id不存在或者是id出错了

		System.out.println("删除操作");
		if (id==null){
			return ResultBean.ERROR(10001,"params null");
		}
		int i = cartDao.delete(id);
		return i>0?ResultBean.SUCCESS():ResultBean.ERROR("delete cart fail");
	}

	@Override
	public ResultBean getById(Integer id) throws Exception {
		//System.out.println("根据id进行查询");
		Cart cart;
		if (id==null){
			return ResultBean.ERROR(10001,"params null");
		}
		 cart= cartDao.getById(id);
		return cart!=null?ResultBean.SUCCESS(cart):ResultBean.ERROR("getById cart fail");
	}

	@Override
	public ResultBean getAll() throws Exception {
		System.out.println("查询全部");
		List<Cart> list=cartDao.getAll();
		return list!=null?ResultBean.SUCCESS():ResultBean.ERROR("getAll is failed");
	}

	@Override
	public ResultBean getByPage(BaseQuery baseQuery) throws Exception {
		System.out.println("分页查询");
		PageBean<Cart> pageBean=new PageBean<>();
		int count=cartDao.getCount(baseQuery);
		pageBean.setTotalRows(count);
		if(count%baseQuery.getPageCount()==0) {
			pageBean.setTotalPages(count/baseQuery.getPageCount());
		} else {
			pageBean.setTotalPages(count/baseQuery.getPageCount()+1);
		}
		List<Cart> list =cartDao.getByPage(baseQuery);
		list.forEach(System.out::println);
		pageBean.setData(list);
		return ResultBean.SUCCESS(pageBean);
	}
	@Override
	public ResultBean batchDel(List<Integer> ids) throws Exception {
		if(ids==null|| ids.size()==0) {
			return ResultBean.ERROR("params is null");
		}
		for(Integer id:ids) {
			cartDao.delete(id);
		}
		return ResultBean.SUCCESS();
	}

}
